package indigo.util;

import static java.util.Objects.requireNonNull;

import java.util.AbstractList;
import java.util.List;
import java.util.RandomAccess;

public class ImmutablePagedList<E> extends AbstractList<E> implements PagedList<E>, RandomAccess {
	private final Object[] elements;
	private final int pageIndex;
	private final int pageSize;
	private final int totalSize;

	protected ImmutablePagedList(int pageIndex, int pageSize, int totalSize, Object[] elements) {
		this.pageIndex = Math.max(pageIndex, 0);
		this.pageSize = Math.max(pageSize, 0);
		this.totalSize = Math.max(totalSize, 0);
		this.elements = requireNonNull(elements, "elements cannot be null");
	}

	@Override
	@SuppressWarnings("unchecked")
	public E get(int index) {
		return (E) elements[index];
	}

	@Override
	public int size() {
		return elements.length;
	}

	@Override
	public int pageIndex() {
		return pageIndex;
	}

	@Override
	public int pageSize() {
		return pageSize;
	}

	@Override
	public int totalSize() {
		return totalSize;
	}

	public static <E> ImmutablePagedList<E> of(int index, int size, int total, List<E> elements) {
		return new ImmutablePagedList<E>(index, size, total, elements.toArray(new Object[0]));
	}
}
